package cn.monkey.family.server.domain.uc.org.role;

import cn.monkey.family.data.Result;
import cn.monkey.family.data.Results;
import cn.monkey.family.data.context.RequestContext;
import cn.monkey.family.data.uc.org.role.OrgRole;
import cn.monkey.family.data.uc.role.Role;
import cn.monkey.family.server.domain.uc.role.AfterRoleSavedEventListener;
import com.google.common.base.Strings;

import java.util.Optional;

public class OrgRoleRelBinder implements AfterRoleSavedEventListener {

    protected final OrgRoleRepository orgRoleRepository;

    public OrgRoleRelBinder(OrgRoleRepository orgRoleRepository) {
        this.orgRoleRepository = orgRoleRepository;
    }

    @Override
    public Result<Void> onEvent(RequestContext context, Role role) {
        String orgId = context.getOrgId();
        if (Strings.isNullOrEmpty(orgId)) {
            return Results.fail("ORG_ID_IS_REQUIRED");
        }
        String roleId = role.getId();
        if (Strings.isNullOrEmpty(roleId)) {
            return Results.fail("ROLE_ID_IS_REQUIRED");
        }
        OrgRole orgRole = new OrgRole();
        orgRole.setOrgId(orgId);
        orgRole.setRoleId(roleId);
        Optional<OrgRole> orgRoleOptional = this.orgRoleRepository.findByRoleId(roleId);
        if (orgRoleOptional.isPresent()) {
            return Results.fail("ROLE_HAS_BIND");
        }
        this.orgRoleRepository.save(orgRole);
        return Results.ok();
    }
}
